package ru.spb.osll.myfit.server.services;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.apache.log4j.Logger;
import ru.spb.osll.myfit.client.service.SuiteService;
import ru.spb.osll.myfit.common.Suite;
import ru.spb.osll.myfit.common.util.Pair;
import ru.spb.osll.myfit.server.SuiteUtils;
import ru.spb.osll.myfit.server.parser.SuiteHandler;

import javax.xml.parsers.ParserConfigurationException;
import java.io.FileNotFoundException;
import java.util.List;

import static ru.spb.osll.myfit.server.SuiteUtils.getSuitePathFromId;

public class SuiteServiceImpl extends RemoteServiceServlet implements SuiteService {
  private static final long serialVersionUID = 3991627184000434448L;

  private static Logger m_logger = Logger.getLogger(SuiteServiceImpl.class);
  private SuiteHandler m_suiteHandler = new SuiteHandler();

  public SuiteServiceImpl() {
    m_logger.info("SuiteServiceImpl constructor");
  }

  @Override
  public Suite getSuite(String id) {
    String suiteFilePath = getSuitePathFromId(id);

    Suite suite = null;
    try {
      suite = m_suiteHandler.getSuite(suiteFilePath);
    } catch (FileNotFoundException e) {
      m_logger.error(e.getMessage() + "\n" + e.getStackTrace());
      suite = new Suite();
    } catch (ParserConfigurationException e) {
      m_logger.error(e.getMessage() + "\n" + e.getStackTrace());
      suite = new Suite();
    }
    suite.setId(id);

    return suite;
  }

  @Override
  public void saveSuite(Suite suite) {
    m_suiteHandler.saveSuite(suite);
  }

  @Override
  public List<String> getSuitePages(Suite suite) {
    return SuiteUtils.getSuitePagesFilteredByTags(suite);
  }

  @Override
  public List<Pair<String, Boolean>> getSuites(String path) {
    return SuiteUtils.getSuites(path);
  }
}
